package com.atguigu.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by RUI on 2021/6/10 19:22
 */
public class Es_sink2 {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        List<HttpHost> hosts = new ArrayList<>();
        hosts.add(new HttpHost("hadoop162",9200));
        hosts.add(new HttpHost("hadoop163",9200));
        hosts.add(new HttpHost("hadoop164",9200));

        ElasticsearchSink.Builder<WaterSensor> builder = new ElasticsearchSink.Builder<>(
                hosts,
                new ElasticsearchSinkFunction<WaterSensor>() {
                    @Override
                    public void process(WaterSensor ws, RuntimeContext rc, RequestIndexer requestIndexer) {

                        IndexRequest source = Requests.indexRequest().index("sensor").type("_doc").id(ws.getId()).source(JSON.toJSONString(ws), XContentType.JSON);

                        requestIndexer.add(source);
                    }
                }
        );
        builder.setBulkFlushMaxActions(3);

        env.socketTextStream("hadoop162",9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] data = value.split(",");
                        return new WaterSensor(data[0],Long.valueOf(data[1]),Integer.valueOf(data[2]));
                    }
                })
                .addSink(builder.build());

        env.execute();
    }
}
